package de.ryancarmon.validator.validators;

import de.ryancarmon.validator.P;
import de.ryancarmon.validator.ValidatorParam;
import de.ryancarmon.validator.exc.UnsupportedValidationException;
import de.ryancarmon.validator.exc.ValidationException;

public class ObjectValidator extends BaseValidator<Object>{

	@Override
	protected void executeValidation(Object param, ValidatorParam validation) {
		switch(validation) {
			case NOT_NULL:
				validateNotNull(param);
				break;
			default:
				throw new UnsupportedValidationException(validation);
		}
	}

	@Override
	protected void executeValidation(Object param, ValidatorParam validation,
			Object validParam) {
		switch(validation) {
			case EQUALS:
				validateEquals(param, validParam);
			case OF_CLASS:
				validateOfClass(param, validParam);
				break;
			default:
				throw new UnsupportedValidationException(validation);
		}
	}
	
	protected void validateNotNull(Object param) {
		if(param == null)
			throw new ValidationException(P.NOT_NULL, param);
	}
	
	protected void validateEquals(Object param, Object equalsObj) {
		if(equalsObj == null && param == null)
			return;
		else if(param == null)
			throw new IllegalArgumentException("'param' may not be null");
		else if(equalsObj == null)
			throw new IllegalArgumentException("'equalsObj' may not be null");
		
		if(!param.equals(equalsObj))
			throw new ValidationException(P.EQUALS, equalsObj, param);
	}
	
	protected void validateOfClass(Object param, Object classObj) {
		if(param == null)
			throw new IllegalArgumentException("'param' may not be null");
		if(classObj == null)
			throw new IllegalArgumentException("'classObj' may not be null");		
		
		Class<?> clazz = toClass(classObj);
		
		if(!clazz.isInstance(param))
			throw new ValidationException(P.OF_CLASS, classObj, param);
	}	
}
